import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Button,
  Space,
  Tag,
  Modal,
  Form,
  Input,
  Select,
  message,
  Popconfirm,
  TreeSelect,
  Row,
  Col,
  DatePicker,
} from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, SearchOutlined, ReloadOutlined } from '@ant-design/icons';
import { menuApi } from '@/services/api';

const { Option } = Select;
const { RangePicker } = DatePicker;

interface Menu {
  id: number;
  name: string;
  path?: string;
  component?: string;
  icon?: string;
  parentId?: number;
  type: string;
  visible: number;
  status: number;
  sort: number;
  createTime: string;
  children?: Menu[];
}

const Menus: React.FC = () => {
  const [menus, setMenus] = useState<Menu[]>([]);
  const [allMenus, setAllMenus] = useState<Menu[]>([]); // 存储所有菜单数据用于过滤
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingMenu, setEditingMenu] = useState<Menu | null>(null);
  const [form] = Form.useForm();
  const [searchForm] = Form.useForm();
  const [searchParams, setSearchParams] = useState<any>({});
  const [pagination, setPagination] = useState({ 
    current: 1, 
    pageSize: 10, 
    total: 0 
  });

  const columns = [
    {
      title: '菜单名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '路径',
      dataIndex: 'path',
      key: 'path',
    },
    {
      title: '组件',
      dataIndex: 'component',
      key: 'component',
    },
    {
      title: '图标',
      dataIndex: 'icon',
      key: 'icon',
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      render: (type: string) => (
        <Tag color={type === 'menu' ? 'blue' : 'green'}>{type}</Tag>
      ),
    },
    {
      title: '可见',
      dataIndex: 'visible',
      key: 'visible',
      render: (visible: number) => (
        <Tag color={visible === 1 ? 'green' : 'red'}>
          {visible === 1 ? '显示' : '隐藏'}
        </Tag>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: number) => (
        <Tag color={status === 1 ? 'green' : 'red'}>
          {status === 1 ? '启用' : '禁用'}
        </Tag>
      ),
    },
    {
      title: '排序',
      dataIndex: 'sort',
      key: 'sort',
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: Menu) => (
        <Space size="middle">
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除此菜单吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="link" danger icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 获取所有菜单数据（树状结构）
  const fetchAllMenus = async () => {
    setLoading(true);
    try {
      const response = await menuApi.getMenuTree();
      const menuData = response.data || response || [];
      setAllMenus(menuData);
      setMenus(menuData); // 初始显示所有菜单
    } catch (error) {
      message.error('获取菜单列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 将树状菜单扁平化处理
  const flattenMenus = (menus: Menu[]): Menu[] => {
    const result: Menu[] = [];
    const traverse = (menuList: Menu[]) => {
      menuList.forEach(menu => {
        result.push({ ...menu, children: undefined }); // 移除children避免重复
        if (menu.children && menu.children.length > 0) {
          traverse(menu.children);
        }
      });
    };
    traverse(menus);
    return result;
  };

  // 过滤菜单数据
  const filterMenus = (params: any) => {
    if (!params || Object.keys(params).length === 0) {
      setMenus(allMenus);
      setPagination(prev => ({ ...prev, total: allMenus.length }));
      return;
    }

    const flatMenus = flattenMenus(allMenus);
    let filteredMenus = flatMenus;

    // 关键词搜索
    if (params.keyword) {
      filteredMenus = filteredMenus.filter(menu =>
        menu.name?.toLowerCase().includes(params.keyword.toLowerCase()) ||
        menu.path?.toLowerCase().includes(params.keyword.toLowerCase()) ||
        menu.remark?.toLowerCase().includes(params.keyword.toLowerCase())
      );
    }

    // 菜单名称精确搜索
    if (params.name) {
      filteredMenus = filteredMenus.filter(menu => menu.name === params.name);
    }

    // 菜单路径搜索
    if (params.path) {
      filteredMenus = filteredMenus.filter(menu => 
        menu.path?.toLowerCase().includes(params.path.toLowerCase())
      );
    }

    // 菜单类型筛选
    if (params.type) {
      filteredMenus = filteredMenus.filter(menu => menu.type === params.type);
    }

    // 父菜单筛选
    if (params.parentId !== undefined) {
      if (params.parentId === 0) {
        filteredMenus = filteredMenus.filter(menu => !menu.parentId);
      } else {
        filteredMenus = filteredMenus.filter(menu => menu.parentId === params.parentId);
      }
    }

    // 显示状态筛选
    if (params.visible !== undefined) {
      filteredMenus = filteredMenus.filter(menu => menu.visible === params.visible);
    }

    // 启用状态筛选
    if (params.status !== undefined) {
      filteredMenus = filteredMenus.filter(menu => menu.status === params.status);
    }

    // 创建时间范围搜索
    if (params.createTimeStart && params.createTimeEnd) {
      filteredMenus = filteredMenus.filter(menu => {
        const createTime = new Date(menu.createTime);
        const startTime = new Date(params.createTimeStart);
        const endTime = new Date(params.createTimeEnd);
        return createTime >= startTime && createTime <= endTime;
      });
    }

    // 排序
    if (params.sortBy) {
      filteredMenus.sort((a, b) => {
        const aValue = a[params.sortBy as keyof Menu];
        const bValue = b[params.sortBy as keyof Menu];
        const direction = params.sortOrder === 'ASC' ? 1 : -1;
        
        if (typeof aValue === 'string' && typeof bValue === 'string') {
          return aValue.localeCompare(bValue) * direction;
        }
        if (typeof aValue === 'number' && typeof bValue === 'number') {
          return (aValue - bValue) * direction;
        }
        return 0;
      });
    }

    setMenus(filteredMenus);
    setPagination(prev => ({ ...prev, total: filteredMenus.length, current: 1 }));
  };

  const buildTreeData = (menus: Menu[]): any[] => {
    return menus.map(menu => ({
      key: menu.id,
      value: menu.id,
      title: menu.name,
      children: menu.children ? buildTreeData(menu.children) : undefined,
    }));
  };

  const handleAdd = () => {
    setEditingMenu(null);
    setModalVisible(true);
    form.resetFields();
  };

  const handleEdit = (menu: Menu) => {
    setEditingMenu(menu);
    setModalVisible(true);
    form.setFieldsValue(menu);
  };

  const handleDelete = async (id: number) => {
    try {
      await menuApi.deleteMenu(id);
      message.success('删除成功');
      await fetchAllMenus(); // 重新获取所有数据
      filterMenus(searchParams); // 重新应用过滤
    } catch (error: any) {
      message.error(error.response?.data?.message || '删除失败');
    }
  };

  const handleSubmit = async (values: any) => {
    try {
      if (editingMenu) {
        await menuApi.updateMenu(editingMenu.id, values);
        message.success('更新成功');
      } else {
        await menuApi.createMenu(values);
        message.success('创建成功');
      }
      setModalVisible(false);
      await fetchAllMenus(); // 重新获取所有数据
      filterMenus(searchParams); // 重新应用过滤
    } catch (error: any) {
      message.error(error.response?.data?.message || '操作失败');
    }
  };

  const handleSearch = (values: any) => {
    const params = { ...values };
    
    // 处理日期范围
    if (values.createTimeRange && values.createTimeRange.length === 2) {
      params.createTimeStart = values.createTimeRange[0].format('YYYY-MM-DD');
      params.createTimeEnd = values.createTimeRange[1].format('YYYY-MM-DD');
      delete params.createTimeRange;
    }
    
    setSearchParams(params);
    setPagination(prev => ({ ...prev, current: 1 })); // 重置到第一页
    filterMenus(params);
  };

  const handleReset = () => {
    searchForm.resetFields();
    setSearchParams({});
    setPagination(prev => ({ ...prev, current: 1 })); // 重置到第一页
    filterMenus({});
  };

  useEffect(() => {
    fetchAllMenus();
  }, []);

  return (
    <div>
      {/* 查询表单 */}
      <Card title="查询条件" style={{ marginBottom: 16 }}>
        <Form
          form={searchForm}
          layout="vertical"
          onFinish={handleSearch}
        >
          <Row gutter={16}>
            <Col span={6}>
              <Form.Item name="keyword" label="关键词搜索">
                <Input placeholder="菜单名/路径/备注" allowClear />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name="name" label="菜单名称">
                <Input placeholder="请输入菜单名称" allowClear />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name="path" label="菜单路径">
                <Input placeholder="请输入菜单路径" allowClear />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name="type" label="菜单类型">
                <Select placeholder="请选择类型" allowClear>
                  <Option value="menu">菜单</Option>
                  <Option value="button">按钮</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={6}>
              <Form.Item name="parentId" label="父菜单">
                <TreeSelect
                  placeholder="请选择父菜单"
                  allowClear
                  treeData={buildTreeData(allMenus)}
                />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name="visible" label="显示状态">
                <Select placeholder="请选择显示状态" allowClear>
                  <Option value={1}>显示</Option>
                  <Option value={0}>隐藏</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name="status" label="启用状态">
                <Select placeholder="请选择启用状态" allowClear>
                  <Option value={1}>启用</Option>
                  <Option value={0}>禁用</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name="createTimeRange" label="创建时间">
                <RangePicker style={{ width: '100%' }} />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={6}>
              <Form.Item name="sortBy" label="排序字段">
                <Select placeholder="请选择排序字段" allowClear>
                  <Option value="sort">排序值</Option>
                  <Option value="createTime">创建时间</Option>
                  <Option value="updateTime">更新时间</Option>
                  <Option value="name">菜单名称</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name="sortOrder" label="排序方向">
                <Select placeholder="请选择排序方向" allowClear>
                  <Option value="ASC">升序</Option>
                  <Option value="DESC">降序</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label=" " style={{ marginTop: 4 }}>
                <Space>
                  <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
                    查询
                  </Button>
                  <Button onClick={handleReset} icon={<ReloadOutlined />}>
                    重置
                  </Button>
                </Space>
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Card>

      {/* 主表单 */}
      <Card>
        <div style={{ marginBottom: 16 }}>
          <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
            新增菜单
          </Button>
        </div>

        <Table
          columns={columns}
          dataSource={menus}
          rowKey="id"
          loading={loading}
          scroll={{ y: 600 }}
          pagination={Object.keys(searchParams).length > 0 ? {
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`,
            onChange: (page, pageSize) => {
              setPagination({ current: page, pageSize: pageSize || 10, total: pagination.total });
            },
          } : false}
          expandable={{
            childrenColumnName: 'children',
            // 当有搜索条件时禁用展开功能（因为此时显示扁平列表）
            disabled: Object.keys(searchParams).length > 0,
          }}
        />

        <Modal
          title={editingMenu ? '编辑菜单' : '新增菜单'}
          open={modalVisible}
          onCancel={() => setModalVisible(false)}
          onOk={() => form.submit()}
          width={600}
        >
          <Form form={form} layout="vertical" onFinish={handleSubmit}>
            <Form.Item
              name="name"
              label="菜单名称"
              rules={[{ required: true, message: '请输入菜单名称' }]}
            >
              <Input />
            </Form.Item>

            <Form.Item name="path" label="菜单路径">
              <Input placeholder="如：/auth/users" />
            </Form.Item>

            <Form.Item name="component" label="组件路径">
              <Input placeholder="如：/Auth/Users" />
            </Form.Item>

            <Form.Item name="icon" label="菜单图标">
              <Input placeholder="如：UserOutlined" />
            </Form.Item>

            <Form.Item name="parentId" label="父菜单">
              <TreeSelect
                placeholder="请选择父菜单"
                allowClear
                treeData={buildTreeData(allMenus)}
              />
            </Form.Item>

            <Form.Item
              name="type"
              label="菜单类型"
              rules={[{ required: true, message: '请选择菜单类型' }]}
            >
              <Select>
                <Option value="menu">菜单</Option>
                <Option value="button">按钮</Option>
              </Select>
            </Form.Item>

            <Form.Item name="visible" label="是否可见" initialValue={1}>
              <Select>
                <Option value={1}>显示</Option>
                <Option value={0}>隐藏</Option>
              </Select>
            </Form.Item>

            <Form.Item name="status" label="状态" initialValue={1}>
              <Select>
                <Option value={1}>启用</Option>
                <Option value={0}>禁用</Option>
              </Select>
            </Form.Item>

            <Form.Item name="sort" label="排序" initialValue={0}>
              <Input type="number" />
            </Form.Item>

            <Form.Item name="remark" label="备注">
              <Input.TextArea rows={3} />
            </Form.Item>
          </Form>
        </Modal>
      </Card>
    </div>
  );
};

export default Menus;